package com.rfid.util;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rfid.db.bean.Rfid;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class SearchManager {

    private static SearchManager dataManager;

    private List<Rfid> mSearchRfids;

    private SearchManager() {
        mSearchRfids = new ArrayList<>();
    }

    public static SearchManager getInstance() {
        if(dataManager == null) {
            dataManager = new SearchManager();
        }
        return dataManager;
    }

    public void save() {
        File file = new File("/sdcard/search");
        file.delete();
        if(mSearchRfids.size() > 0) {
            Gson gson = new Gson();
            String json = gson.toJson(mSearchRfids);
            FileUtil.writeFile(file.getPath(),json);
        }
    }

    public void addSearchRfid(Rfid rfid) {
        mSearchRfids.add(rfid);
    }

    public List<Rfid> getSearchRfids() {
        if(mSearchRfids.size() == 0) {
            readCachedData();
        }
        return mSearchRfids;
    }

    private void readCachedData() {
        File file = new File("/sdcard/search");
        try {
            if (file.exists() && file.length() > 8) {
                String text = FileUtil.readFile(file.getPath());
                Gson gson = new Gson();
                List<Rfid> rfids = gson.fromJson(text, new TypeToken<List<Rfid>>() {
                }.getType());
                mSearchRfids.addAll(rfids);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
